﻿using System;
using System.IO;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using QuickTest.Services.TextRetrieval;

namespace QuickTest.Tests
{
    /// <summary>
    /// The TestUtils class contains static helper methods for running unit tests.
    /// </summary>
    public static class TestUtils
    {
        #region Exeception Testing

        /// <summary>
        /// Tries to execute some code and asserts exception.
        /// </summary>
        /// <typeparam name="T">Expected exception type</typeparam>
        /// <param name="code">Code to execute</param>
        /// <returns>Returns the exception for further assertions</returns>
        public static Exception AssertThrows<T>(Action code) where T : Exception
        {
            Exception exception = Catch(code);
            Assert.That(exception, Is.InstanceOfType(typeof (T)));
            return exception;
        }

        /// <summary>
        /// Tries to execute some code and asserts exception.
        /// </summary>
        /// <typeparam name="T">Expected exception type</typeparam>
        /// <param name="code">Code to execute</param>
        /// <param name="message">Assertion failed message</param>
        /// <returns>Returns the exception for further assertions</returns>
        public static Exception AssertThrows<T>(Action code, string message) where T : Exception
        {
            Exception exception = Catch(code);
            Assert.That(exception, Is.InstanceOfType(typeof (T)), message);
            return exception;
        }

        private static Exception Catch(Action code)
        {
            try
            {
                code();
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return ex;
            }
        }

        #endregion

        #region Test File Creation & Deletion

        public const string TestDirectory = "c:/Temp/QuickTest";

        public static void CreateTestFile(string embeddedResourcePath, string filePath)
        {
            CreateTestDirectory(TestDirectory);
            var settings = new EmbeddedResourceTextRetrieverSettings(embeddedResourcePath);
            File.WriteAllText(filePath, new EmbeddedResourceTextRetriever(settings).GetText());
        }

        public static void CreateTestDirectory(string path)
        {
            Directory.CreateDirectory(path);
        }

        public static void DeleteTestFiles()
        {
            Directory.Delete(TestDirectory, true);
        }

        public const string ValidPath = @"Addin\QuickTestAddIn.AddIn";

        #endregion
    }
}